package com.example.meitao.ui;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.meitao.R;
import com.example.meitao.fragment.BuyFragment;
import com.example.meitao.fragment.HomeFragment;
import com.example.meitao.fragment.MineFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RadioGroup mRadioGroup;
    private Fragment mCurrentFragment;
    private FragmentManager mManager;
    private SharedPreferences sharedPreferences;

    private Button bt_add, bt_link, bt_net, bt_grade, bt_video;
    private boolean mIsMenuOpen = false;
    private boolean isLogin =false;

    private Boolean isfinished =false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        setListener();

    }
  



    private void setListener() {
        isLogin = sharedPreferences.getBoolean("isLogin", false);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Class<? extends Fragment> clazz = null;
                switch (i) {
                    case R.id.rb_main_home:
                        clazz = HomeFragment.class;
                        showAndHide(R.id.fl_main_content, clazz);
                        break;
                    case R.id.rb_main_buy:

                        if (isLogin) {
                            clazz = BuyFragment.class;
                            showAndHide(R.id.fl_main_content, clazz);
                        } else {
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                            }

                        break;
                    case R.id.rb_main_mine:
                        clazz = MineFragment.class;
                        showAndHide(R.id.fl_main_content, clazz);
                        break;
                    default:
                        break;
                }
                // showAndHide(R.id.fl_main_content,clazz);
            }
        });
    }
    //设置再按一次退出返回键
    @Override
    public void onBackPressed()
    {
        isCanBack();

    }
    //设置再按一次退出
    public void isCanBack() {
        //super.onBackPressed();
        if (isfinished)
        {
            finish();
        } else
        {
            Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
            new Thread()
            {
                public void run()
                {
                    isfinished = true;
                    try
                    {
                        Thread.sleep(2000);
                        isfinished = false;
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                };
            }.start();
        }
    }

    private void initData() {
        mManager = getSupportFragmentManager();
        showAndHide(R.id.fl_main_content, HomeFragment.class);

        //创建共享参数存储登陆状态
        sharedPreferences = getSharedPreferences("FourMan", Context.MODE_PRIVATE);
    }

    private void initView() {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.hide();
        }
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_main_index);


        //初始化第二个按钮里的button
        bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(this);

        bt_link = (Button) findViewById(R.id.bt_link);
        bt_link.setOnClickListener(this);
        bt_net = (Button) findViewById(R.id.bt_net);
        bt_net.setOnClickListener(this);
        bt_grade = (Button) findViewById(R.id.bt_grade);
        bt_grade.setOnClickListener(this);
        bt_video = (Button) findViewById(R.id.bt_video);
        bt_video.setOnClickListener(this);

    }


    private void showAndHide(int contentId, Class<? extends Fragment> clazz) {
        //判断当前的fragmemt和需要替换的Fragment是不是一个
        if (mCurrentFragment != null && mCurrentFragment.getClass().getSimpleName().equals(clazz.getSimpleName())) {
            return;
        }

        FragmentTransaction transaction = mManager.beginTransaction();
        Fragment fragment = null;
        try {
            //判断Fragment有没有添加过
            Fragment fragmentByTag = mManager.findFragmentByTag(clazz.getSimpleName());
            if (fragmentByTag != null) {
                //显示需要 显示的Fragment
                transaction.show(fragmentByTag);
                //隐藏当前的Fragment
                transaction.hide(mCurrentFragment);
                //记录当前显示的Fragment
                mCurrentFragment = fragmentByTag;
            } else {
                //通过无参的 公开的构造函数来创建实例
                fragment = clazz.newInstance();
                //当前的Fragment没有添加过
                //把Fragment添加到FragmentManager里面
                transaction.add(contentId, fragment, clazz.getSimpleName());
                //隐藏当前的Fragment
                if (mCurrentFragment != null) {
                    transaction.hide(mCurrentFragment);
                }
                //记录当前的Fragment
                mCurrentFragment = fragment;
            }

            transaction.commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    /*利用mIsMenuOpen来标识当前是否已经弹出菜单；如果没有弹出，
   则利用doAnimateOpen(mItemButton1, 0, 5, 300)将mItemButton1弹出来；其它按钮类似。
   如果已经弹出来，则利用doAnimateClose(mItemButton1, 0, 5, 300);将mItemButton1收回。*/
    @Override
    public void onClick(View view) {
        if (view == bt_add) {
            if (!mIsMenuOpen) {
                mIsMenuOpen = true;
                doAnimateOpen(bt_link, 0, 4, 200);
                doAnimateOpen(bt_net, 1, 4, 200);
                doAnimateOpen(bt_grade, 2, 4, 200);
                doAnimateOpen(bt_video, 3, 4, 200);


            } else {
                mIsMenuOpen = false;
                doAnimateClose(bt_link, 0, 4, 200);
                doAnimateClose(bt_net, 1, 4, 200);
                doAnimateClose(bt_grade, 2, 4, 200);
                doAnimateClose(bt_video, 3, 4, 200);

            }
        } else {
            switch (view.getId()) {
                case  R.id.bt_link:
//                    if (isLogin) {
                        startActivity(new Intent(MainActivity.this,LinkActivity.class));
//                    } else {
//                        startActivity(new Intent(MainActivity.this,LoginActivity.class));
//                    }
                    overridePendingTransition(R.anim.activity_in,R.anim.activity_out);
                    break;
                case R.id.bt_net:
                    startActivity(new Intent(MainActivity.this,NetQueryActivity.class));
                    break;
                case R.id.bt_grade:
                    startActivity(new Intent(MainActivity.this,GradeActivity.class));
                    break;
                case R.id.bt_video:
                    startActivity(new Intent(MainActivity.this,VideoActivity.class));
                    break;
            }

        }
    }



    //弹出按钮动画
    private void doAnimateOpen(View view, int index, int total, int radius) {
        if (view.getVisibility() != View.VISIBLE) {
            view.setVisibility(View.VISIBLE);
        }
        double degree = Math.toRadians(180) / (total - 1) * index;
        int translationX = -(int) (radius * Math.cos(degree));
        int translationY = -(int) (radius * Math.sin(degree));

        AnimatorSet set = new AnimatorSet();
        //包含平移、缩放和透明度动画
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", 0, 1800);
        animator.setInterpolator(new AccelerateInterpolator());
        set.playTogether(
                ObjectAnimator.ofFloat(view, "translationX", 0, translationX),
                ObjectAnimator.ofFloat(view, "translationY", 0, translationY),
                ObjectAnimator.ofFloat(view, "scaleX", 0f, 1f),
                ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f),
                animator,
                ObjectAnimator.ofFloat(view, "alpha", 0f, 1));
        //动画周期为500ms
        set.setDuration(1 * 500).start();

        //bt_add旋转
        ObjectAnimator animatorAdd = ObjectAnimator.ofFloat(bt_add, "rotation", 0, 45);
        animatorAdd.setDuration(500);
        animatorAdd.start();

    }

    //收回按钮
    private void doAnimateClose(final View view, int index, int total,
                                int radius) {
        if (view.getVisibility() != View.VISIBLE) {
            view.setVisibility(View.VISIBLE);
        }

        double degree = Math.toRadians(180) / (total - 1) * index;
        int translationX = -(int) (radius * Math.cos(degree));
        int translationY = -(int) (radius * Math.sin(degree));
        AnimatorSet set = new AnimatorSet();
        //包含平移、缩放和透明度动画
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", 0, -1800);
        animator.setInterpolator(new AccelerateInterpolator());
        set.playTogether(ObjectAnimator.ofFloat(view, "translationX", translationX, 0),
                ObjectAnimator.ofFloat(view, "translationY", translationY, 0),
                ObjectAnimator.ofFloat(view, "scaleX", 1f, 0f),
                ObjectAnimator.ofFloat(view, "scaleY", 1f, 0f),
                animator,
                ObjectAnimator.ofFloat(view, "alpha", 1f, 0f));

        set.setDuration(1 * 500).start();


        ObjectAnimator animatorAdd2 = ObjectAnimator.ofFloat(bt_add, "rotation", 45, 0);
        animatorAdd2.setDuration(500);
        animatorAdd2.start();

        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                if (view.getVisibility() == View.VISIBLE) {
                    view.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

    }
}
